#include <iostream>
#include <vector>
#include <stack>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        stack<TreeNode*> stack;
        TreeNode* ptr = root;
        vector<int> result;
        if (root == nullptr) {
            return result;
        }
        begin:
        while (ptr->left != nullptr) {
            stack.push(ptr);
            result.push_back(ptr->val);
            ptr = ptr->left;
        }
        if (ptr->right != nullptr) {
            result.push_back(ptr->val);
            ptr = ptr->right;
            goto begin;
        }
        result.push_back(ptr->val);
        do {
            if (stack.size() == 0) {
                return result;
            }
            ptr = stack.top();
            stack.pop();
        } while (ptr->right == nullptr);
        ptr = ptr->right;
        goto begin;
    }
};


int main() {
    TreeNode t1(3), t2(1), t3(2);
    t1.left = &t2;
    t1.right = &t3;
    Solution solution;
    vector<int> out = solution.preorderTraversal(&t1);
    for (int o: out) {
        cout << o << ",";
    }
}